package com.remedios.service;

import com.remedios.mapper.MailLogMapper;
import com.ruoyi.common.core.constant.RabbitMqConstants;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.MailSendLog;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.vo.MailSendLogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @
 */
@Service
@Slf4j
public class MailLogServiceImpl implements MailSendLogService {
    @Autowired
    private MailLogMapper mailSendLogMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询邮件日志
     *
     * @param msgid 邮件日志主键
     * @return 邮件日志
     */
    @Override
    public MailSendLog selectMailSendLogByMsgId(String msgId) {
        return mailSendLogMapper.selectMailSendLogByMsgId(msgId);
    }

    /**
     * 查询邮件日志列表
     *
     * @param mailSendLog 邮件日志
     * @return 邮件日志
     */
    @Override
    public List<MailSendLogVo> selectMailSendLogList(MailSendLog mailSendLog) {
        List<MailSendLogVo> mailSendLogs = mailSendLogMapper.selectMailSendLogList(mailSendLog).stream().map(a -> {
            MailSendLogVo mailSendLogVo = new MailSendLogVo();
            BeanUtils.copyProperties(a, mailSendLogVo);
            return mailSendLogVo;
        }).collect(Collectors.toList());
        return mailSendLogs;
    }

    /**
     * 新增邮件日志
     *
     * @param mailSendLog 邮件日志
     * @return 结果
     */
    @Override
    public int insertMailSendLog(MailSendLog mailSendLog) {
        return mailSendLogMapper.insertMailSendLog(mailSendLog);
    }

    /**
     * 修改邮件日志
     *
     * @param mailSendLog 邮件日志
     * @return 结果
     */
    @Override
    public int updateMailSendLog(MailSendLog mailSendLog) {
        return mailSendLogMapper.updateMailSendLog(mailSendLog);
    }

    /**
     * 批量删除邮件日志
     *
     * @param msgids 需要删除的邮件日志主键
     * @return 结果
     */
    @Override
    public int deleteMailSendLogByMsgIds(String[] msgIds) {
        return mailSendLogMapper.deleteMailSendLogByMsgIds(msgIds);
    }

    /**
     * 删除邮件日志信息
     *
     * @param msgid 邮件日志主键
     * @return 结果
     */
    @Override
    public int deleteMailSendLogByMsgId(String msgId) {
        return mailSendLogMapper.deleteMailSendLogByMsgId(msgId);
    }

    @Override
    public int reSend(MailSendLog mailSendLog) {
        SysUser sysUser = remoteUserService.getUserSingle(mailSendLog.getUserId());
        MailSendLog mailSendLogWithPassword = selectMailSendLogByMsgId(mailSendLog.getMsgId());
        if (sysUser == null) {
            throw new RuntimeException("这个用户已经离开当前企业");
        }
        String messageKey = RabbitMqConstants.CORRELATION_ID + mailSendLog.getMsgId();
        sysUser.setParams(new HashMap() {
            {
                put("unencrypted", mailSendLogWithPassword.getPassword());
            }
        });
        return sendMessage(mailSendLog.getMsgId(), messageKey, sysUser);
    }

    @Override
    public int sendMessage(String correlationDataId, String messageKey, SysUser user) {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            helper.setTo(user.getEmail());
            helper.setFrom(mailProperties.getUsername());
            helper.setSubject("入职欢迎");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("nickName", user.getNickName());
            context.setVariable("name", user.getUserName());
            context.setVariable("password", user.getParams().get("unencrypted"));
            context.setVariable("date", LocalDate.now());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            //发送邮件
            javaMailSender.send(msg);

            log.info("++++++ 清除message缓存:{}", correlationDataId);
            //清除message缓存
            redisTemplate.delete(messageKey);
            MailSendLog mailSendLog = new MailSendLog();
            mailSendLog.setMsgId(correlationDataId);
            mailSendLog.setStatus(RabbitMqConstants.SUCCESS);
            mailSendLog.setPassword(null);
            updateMailSendLog(mailSendLog);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送出现异常");
        }
        return 1;
//        MimeMessage msg = javaMailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(msg);
//        try {
//            String userJSON = redisTemplate.opsForValue().get(messageKey);
//            if (StringUtils.isNotEmpty(userJSON)) {
//                Object parse = JSON.parse(userJSON);
//                user = JSON.parseObject((String) parse, SysUser.class);
//            }
//            helper.setTo(user.getEmail())
//            helper.setFrom(mailProperties.getUsername());
//            helper.setSubject("入职欢迎");
//            helper.setSentDate(new Date());
//            Context context = new Context();
//            context.setVariable("nickName", user.getNickName());
//            context.setVariable("name", user.getUserName());
//            context.setVariable("password", user.getParams().get("unencrypted"));
//            context.setVariable("date", LocalDate.now());
//            String mail = templateEngine.process("mail", context);
//            helper.setText(mail, true);
//            javaMailSender.send(msg);
//            MailSendLog mailSendLog = new MailSendLog();
//            mailSendLog.setMsgId(correlationDataId);
//            mailSendLog.setStatus(RabbitMqConstants.SUCCESS);
//            updateMailSendLog(mailSendLog);
//            redisTemplate.delete(messageKey);
//        } catch (MessagingException e) {
//            throw new RuntimeException(e);
//        }
    }
}
